<!--
 * @Description: 页面顶部 表单集 组件
 * @Version: 1.0
 * @Autor: tao
 * @Date: 2021-01-15 16:19:27
 * @LastEditors: tao
 * @LastEditTime: 2021-03-26 17:01:52
-->
<template>
  <div class="top">
    <div class="top_item">
      <a-input-search placeholder="搜索" enter-button @search="onSearch" />
    </div>
    <div class="top_item">
      <a-button type="primary" @click="showModel"> 添加 </a-button>
    </div>
    <div class="top_item">
      <a-button type="primary" @click="batch"> 批量导入 </a-button>
    </div>
    <div class="top_item">
      <a-button type="primary" @click="showAll"> 显示全部 </a-button>
    </div>
    <Model
      v-if="isShow"
      title="添加"
      :width="400"
      :show="isShow"
      @confirm="confirm"
      @cancel="cancel"
    >
      <div slot="form">
        <div class="dialog">
          请按照模板格式进行导入
          <a @click="download">下载模板</a>
        </div>
        <div>
          <a-upload
            :file-list="fileList"
            :multiple="false"
            :remove="handleRemove"
            :before-upload="beforeUpload"
          >
            <a-button> <a-icon type="upload" /> 选择Excel文件 </a-button>
          </a-upload>
        </div>
      </div>
    </Model>
  </div>
</template>

<script>
import Model from "components/common/model/Model";
import { uploadFile, downloadFile } from "network/u-student";
import { downloadOfA } from "common/index";
export default {
  components: {
    Model,
  },
  data() {
    return {
      isShow: false,
      fileList: [],
      file: "",
    };
  },
  methods: {
    async download() {
      //发送请求
      const result = await downloadFile();
      if (!result) return;
      //下载文件
      downloadOfA(result, ".xlsx", `学生信息导入模板`);
    },
    beforeUpload(file) {
      this.fileList = [file];
      this.file = file;
      return false;
    },
    handleRemove(file) {
      const index = this.fileList.indexOf(file);
      const newFileList = this.fileList.slice();
      newFileList.splice(index, 1);
      this.fileList = newFileList;
      this.file = "";
    },
    showModel() {
      this.$emit("showModel");
    },
    showAll() {
      this.$emit("showAll");
    },
    onSearch(value) {
      this.$emit("search", value);
    },
    async confirm() {
      let formData = new FormData();
      formData.append("file", this.file);
      this.cancel();
      const result = await uploadFile(formData);
      if (!result.msg) return void this.$message.error("导入失败");
      this.showAll();
    },
    batch() {
      this.isShow = true;
    },
    cancel() {
      this.fileList = [];
      this.file = "";
      this.isShow = false;
    },
  },
};
</script>

<style lang="less" scoped>
.top {
  display: flex;
  margin-bottom: 20px;
  .top_item {
    margin: 0 20px;
  }
}
.dialog {
  margin-bottom: 20px;
}
</style>